$(window).load(function() {
    if ($('#slider').length > 0) {
        $('#slider').nivoSlider();
    }
    if ($('#pagination').length > 0) {
        $('#pagination').pagination();
    }
    if ($(".btn_login").length > 0) {
        $(".btn_login").login();
    }
    if ($("#register").length > 0) {
        $("#register").register();
    }
    if ($("a.login-window").length > 0) {
        $("a.login-window").loginBox();
    }
    if ($("#profile").length > 0) {
        $("#profile").profile();
    }
    if ($("#order").length > 0) {
        $("#order").finishedOrder();
    }
    $("#link_giohang").click(function() {
        window.location = base_url + "gio-hang.html"
    });
    $(".update_sl").click(function() {
        $("#form_update").submit();
    });
    if ($("form").length > 0) {
        $("form").location();
    }
});

$.fn.extend({
    location: function() {
        var location = $(this);
        location.find("select[name=city]").bind('change', function() {
            var cityInfo = $(this);
            var city_id = cityInfo.val();
            $.ajax({
                url: base_url + "location/get_state",
                type: 'post',
                data: {city_id: city_id},
                dataType: 'json',
                success: function(json) {
                    if (json.status == true) {
                        location.find("select[name=state]").replaceWith(json.data);
                    } else if (json.status == false) {
                        alert(json.message);
                    }
                }
            });
        });
        location.find("select[name=state]").live('change', function() {
            var stateInfo = $(this);
            var state_id = stateInfo.val();
            $.ajax({
                url: base_url + "location/get_ward",
                type: 'post',
                data: {state_id: state_id},
                dataType: 'json',
                success: function(json) {
                    if (json.status == true) {
                        location.find("select[name=ward]").replaceWith(json.data);
                    } else if (json.status == false) {
                        alert(json.message);
                    }
                }
            });
        });
    },
    profile: function() {
        var profile = $(this);
        profile.find("input[name=fullname]").focus();
        profile.validate({
            rules: {
                fullname: "required",
                address: "required",
                city: {
                    required: true
                },
                state: {
                    required: true
                },
                ward: "required",
                phone: "required",
                email: {
                    required: true,
                    email: true
                },
                password_confirm: {
                    equalTo: "#password"
                }
            },
            messages: {
                fullname: "",
                address: "",
                city: "Chọn tỉnh/thành phố",
                state: "Chọn quận huyện",
                phone: "",
                email: "",
                password_confirm: "Xác nhận mật khẩu không khớp"
            },
//            errorPlacement: function(error, element) {
//              return true;    
//            },
            submitHandler: function() {
                $.ajax({
                    url: profile.attr('action'),
                    type: 'post',
                    data: profile.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            $("#infoMessage").html(json.message);
                        } else if (json.status == false) {
                            $("#infoMessage").html(json.message);
                        }
                    }
                });
                return false;
            }
        });
    },
    finishedOrder: function() {
        var order = $(this);
        order.find("input[name=fullname]").focus();
        order.validate({
            rules: {
                fullname: "required",
                address: "required",
                city: {
                    required: true
                },
                state: {
                    required: true
                },
                ward: "required",
                phone: "required"
            },
            messages: {
                fullname: "",
                address: "",
                city: "Chọn tỉnh/thành phố",
                state: "Chọn quận huyện",
                phone: ""
            },
            submitHandler: function() {
                $.ajax({
                    url: order.attr('action'),
                    type: 'post',
                    data: order.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            document.location.href = json.redirect;
                        } else if (json.status == false) {
                            alert(json.message);
                        }
                    }
                });
                return false;
            }
        });
    },
    loginBox: function() {
        $(this).click(function() {

            // Getting the variable's value from a link 
            var loginBox = $(this).attr('href');

            //Fade in the Popup and add close button
            $(loginBox).fadeIn(300);

            //Set the center alignment padding + border
            var popMargTop = ($(loginBox).height() + 24) / 2;
            var popMargLeft = ($(loginBox).width() + 24) / 2;

            $(loginBox).css({
                'margin-top': -popMargTop,
                'margin-left': -popMargLeft
            });

            // Add the mask to body
            $('body').append('<div id="mask"></div>');
            $('#mask').fadeIn(300);

            return false;
        });

        // When clicking on the button close or the mask layer the popup closed
        $('a.close, #mask').live('click', function() {
            $('#mask , .login-popup').fadeOut(300, function() {
                $('#mask').remove();
            });
            return false;
        });
    },
    login: function() {
        var formLogin = $(this).parents("form");
        formLogin.find("input[name=email]").focus();
        formLogin.bind('submit', function() {
            var email = formLogin.find("input[name=email]");
            var password = formLogin.find("input[name=password]");
            var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
            $(".login_form .error_message").html();
            if (pattern.test(email.val()) && password.val() != "") {
                $.ajax({
                    url: formLogin.attr('action'),
                    type: 'post',
                    data: formLogin.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            document.location.href = json.redirect;
                        } else if (json.status == false) {
                            formLogin.find(".error_message").html(json.message);
                        }
                    }
                });
            } else {
                if (email.val() == "" || !pattern.test(email.val())) {
                    alert(email.attr("placeholder"));
                    email.focus();
                } else if (password.val() == "") {
                    alert(password.attr("placeholder"));
                    password.focus();
                }
            }
            return false;
        })
    },
    register: function() {
        var formRegister = $(this);
        formRegister.find("input[name=fullname]").focus();
        formRegister.validate({
            rules: {
                email: {
                    required: true,
                    email: true
                },
                AcceptTerms: "required",
                fullname: "required",
                password: "required",
                mobile: "required",
                address: "required",
                city: "required",
                state: "required",
                ward: "required",
                repassword: {
                    equalTo: "#RegisterPassword"
                }
            },
            errorPlacement: function(error, element) {
                return true;
            },
            submitHandler: function() {

                $.ajax({
                    url: formRegister.attr('action'),
                    type: 'post',
                    data: formRegister.serialize(),
                    dataType: 'json',
                    success: function(json) {
                        if (json.status == true) {
                            alert(json.message);
                            document.location.href = json.redirect;
                        } else if (json.status == false) {
                            alert(json.message);
                        }
                    }
                });
                return false;
            }
        });
    },
    pagination: function() {
        var pagination = $(this);
        var arrowA = pagination.children('a.arrow');
        var moreA = pagination.children('a.more');
        arrowA.bind('click', function(){
            var height = pagination.children("ul").height();
            pagination.children("ul").css("top", 5+arrowA.height()-height/2);
            pagination.children("ul").show("fade", 1000);
        });
        arrowA.bind('blur', function() {
            var tagName = $(this).attr("tagName");
            if(tagName != 'a') {
//                pagination.children("ul").hide();
            }
        });
        moreA.bind('click', function() {
            var aNext = pagination.find("strong").next();
            $(this).attr("href", aNext.attr('href'));
            return true;
        });
    }
})